package com.coocaa.ops.plus.dashboard.v1.internalapimgr.service;

import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.exception.BusinessException;
import com.coocaa.ops.common.tool.exception.ExceptionUtil;
import com.coocaa.ops.common.tool.json.JsonUtil;
import com.coocaa.ops.plus.dashboard.v1.internalapimgr.model.RequestModel;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @author bijiahao
 * @description
 * @date 2020/2/18 11:17
 */
@Slf4j
@Service
public class ThirdApiRequestServiceImpl implements IThirdApiRequestService {
    /**
     * 获取请求结果
     *
     * @param requestModel
     * @return
     */
    @Override
    public String getResponse(RequestModel requestModel) {
        OkHttpClient client = new OkHttpClient();
        try {
            Request request = buildRequest(requestModel);
            Response execute = client.newCall(request).execute();
            String result = execute.body().string();
            if (execute.isSuccessful()) {
                return result;
            }
        } catch (IOException e) {
            log.error(ExceptionUtil.getStackTraceAsString(e));
        }
        Map errMap = InstanceUtil.newHashMap(1);
        errMap.put("httpUrl", requestModel.getUrl());
        throw new BusinessException(errMap, "Http请求数据失败");
    }

    private Request buildRequest(RequestModel requestModel) {
        RequestBody formBody = buildRequestBody(requestModel);
        Request.Builder requestBuilder = new Request.Builder()
                .url(requestModel.getUrl())
                .post(formBody);
        String header = requestModel.getHeader();
        if (StringUtils.isNotBlank(header)) {
            Map<String, String> headerMap = JsonUtil.json2Map(header);
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        return requestBuilder.build();
    }

    private RequestBody buildRequestBody(RequestModel requestModel) {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        String params = requestModel.getParams();
        if (StringUtils.isNotBlank(params)) {
            Map<String, String> paramsMap = JsonUtil.json2Map(params);
            for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                formBodyBuilder.add(entry.getKey(), entry.getValue());
            }
        }
        return formBodyBuilder.build();
    }
}
